﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls.Primitives;
using WPFDataEditors.Classes;

namespace WPFDataEditors.CalculatorDropDown.Control
{
    public class CalculatorDropDown:System.Windows.Controls.Control,INotifyPropertyChanged
    {

        #region Fields

        private static readonly Uri ControlThemeuri = new Uri("/WPFDataEditors;component/CalculatorDropDown/Themes/Generic.xaml", UriKind.Relative);
        private readonly ResourceDictionary _controlThemeStyle = new ResourceDictionary { Source = ControlThemeuri };

        #endregion

        #region Constructor

        public CalculatorDropDown()
        {
            AddResouces();
            Loaded += CalculatorDropDownLoaded;
        }

        #endregion

        #region Properties

        private Calculator.Control.Calculator Calculator { get; set; }
        private ToggleButton ToggleButton { get; set; }
        private Popup Popup { get; set; }

        #endregion

        #region Commands
        #endregion

        #region CommandHandler
        #endregion

        #region Methods

        private void AddResouces()
        {

            if (!UriParser.IsKnownScheme("pack"))
                UriParser.Register(new GenericUriParser(GenericUriParserOptions.GenericAuthority), "pack", -1);


            //Datagrid
            if (!Resources.MergedDictionaries.Contains(_controlThemeStyle))
                Resources.MergedDictionaries.Add(_controlThemeStyle);
        }

        #endregion

        #region Events

        public event PropertyChangedEventHandler PropertyChanged;

        void CalculatorDropDownLoaded(object sender, RoutedEventArgs e)
        {
            var popups = FindControls.GetVisualChildCollection<Popup>(this as object);
            if (popups != null && popups.Count > 0)
            {
                Popup = popups[0];
                popups[0].MouseLeave += new System.Windows.Input.MouseEventHandler(CalculatorDropDownMouseLeave);
            }
            var toggleButtons = FindControls.GetVisualChildCollection<ToggleButton>(this as object);
            if (popups != null && popups.Count > 0)
            {
                ToggleButton = toggleButtons[0];
            }
        }

        void CalculatorDropDownMouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (Popup.IsOpen)
                ToggleButton.IsChecked = !ToggleButton.IsChecked;
        }

        #endregion

    }
}
